<?php
class Model_Privilege {
	private $_id;
	private $_resourceId;
	private $_resourceType;
	private $_roleId;
	private $_roleType;
	private $_mode;

	public function setId($id) {
		$this->_id = $id;
	}

	public function setResourceId($id) {
		$this->_resourceId = $id;
	}

	public function setResourceType($type) {
		$this->_resourceType = $type;
	}

	public function setRoleId($id) {
		$this->_roleId = $id;
	}

	public function setRoleType($type) {
		$this->_roleType = $type;
	}

	public function setMode($mode) {
		$this->_mode = $mode;
	}

	public function getResource() {
		if($this->_resourceType == 'category') {
			return Model_Category::findById($this->_resourceId);
		}
		else {
			return Model_File::findById($this->_resourceId);
		}
	}

	public function getMode() {
		return $this->_mode;
	}

	public function getRole() {	   
		if($this->_roleType == 'user') {
			return Model_User::findById($this->_roleId);
		} else {
		   //$group = Model_Group::findById($this->_roleId);
		   $groupModel = new Model_Group();
		   $group = $groupModel->findOneBy('id', $this->_roleId);
			return $group;
		}
	}

	public static function findByCategories($categories) {
		$db = Zend_Registry::get('db');

		$ids = array();
		foreach($categories as $category) {
			$ids[] = $category->getId();
		}

		$sql = '
   		SELECT 
   		    id, resource_id, resource_type, role_id, role_type, mode
         FROM 
            privileges
         WHERE 
            resource_type = "category" AND 
            resource_id IN(' . implode(', ', $ids) . ')
         ';
      
		$rows = $db->fetchAssoc($sql);

		return self::_hydrateRows($rows);
	}

	public static function findByFile(Model_File $file) {
		$db = Zend_Registry::get('db');

		$sql = '
		    SELECT 
		       id, resource_id, resource_type, role_id, role_type, mode
         FROM 
            privileges
         WHERE 
            resource_type = "file" AND 
            resource_id = ?
         ';

		$rows = $db->fetchAssoc($sql, array($file->getId()));

		return self::_hydrateRows($rows);
	}

	public static function _hydrateRows($rows) {
		$results = array();

		foreach($rows as $row) {
			$privilege = new Model_Privilege();
			$privilege->setId($row['id']);
			$privilege->setResourceId($row['resource_id']);
			$privilege->setResourceType($row['resource_type']);
			$privilege->setRoleId($row['role_id']);
			$privilege->setRoleType($row['role_type']);
			$privilege->setMode($row['mode']);
			$results[] = $privilege;
		}

		return $results;
	}
}